package cn.com.taiji.common.utils.http;

import cn.com.taiji.common.config.OpenServiceConfig;
import cn.com.taiji.common.utils.StringUtils;
import cn.com.taiji.common.utils.sign.Md5Utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 第三方接口调用工具类
 * @author linhaiy
 * @since 2022.03.31
 */
@Slf4j
@Component
public class HttpCallUtils {

    @Resource
    private OpenServiceConfig openServiceConfig;

    /**
     * 正则匹配host
     * @param url
     * @return
     */
    public String getHost(String url){
        String host = StringUtils.EMPTY;
        Pattern pattern = Pattern.compile("^(\\w+):\\/\\/([^/:]+)(:\\d*|\\/)");
        Matcher match = pattern.matcher(url);
        if (match.find( )) {
            host = match.group(2);
        }
        return host;
    }

    public String sendGet(String url){
        String result = StringUtils.EMPTY;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        httpGet.addHeader("Accept-Encoding", "gzip, deflate");
        httpGet.addHeader("Accept-Language", "zh-CN,zh;q=0.8");
        httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36");
        httpGet.addHeader("Content-Type", "application/json; charset=utf-8");
        httpGet.addHeader("Connection", "Keep-Alive");
        httpGet.addHeader("keyId", openServiceConfig.getKeyId());
        httpGet.addHeader("rcode", openServiceConfig.getRcode());
        httpGet.addHeader("ts", openServiceConfig.getTs());
        httpGet.addHeader("region", openServiceConfig.getRegion());
        httpGet.addHeader("signature", Md5Utils.hash(openServiceConfig.getKeyId()+openServiceConfig.getTs()+
                openServiceConfig.getKeySecret()));
        String host = getHost(url);
        httpGet.addHeader("Host", host);
        httpGet.setConfig(RequestConfig.custom().setConnectTimeout(5000).build());
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            int status = response.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_OK){
                HttpEntity responseEntity = response.getEntity();
                result = EntityUtils.toString(responseEntity, "UTF-8");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public String sendJsonPost(String url, String json){
        String result = StringUtils.EMPTY;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
        httpPost.addHeader("Connection", "Keep-Alive");
        httpPost.addHeader("keyId", openServiceConfig.getKeyId());
        httpPost.addHeader("rcode", openServiceConfig.getRcode());
        httpPost.addHeader("ts", openServiceConfig.getTs());
        httpPost.addHeader("region", openServiceConfig.getRegion());
        httpPost.addHeader("signature", Md5Utils.hash(openServiceConfig.getKeyId()+openServiceConfig.getTs()+
                openServiceConfig.getKeySecret()));
        String host = getHost(url);
        httpPost.addHeader("Host", host);
        StringEntity requestEntity = new StringEntity(json,"utf-8");
        httpPost.setEntity(requestEntity);
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int status = response.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_OK){
                HttpEntity responseEntity = response.getEntity();
                result = EntityUtils.toString(responseEntity, "UTF-8");
            }else {
                result = response.getEntity().toString();;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
